﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ELMWCFServiceClass.ELMWCF;
using System.IO;

namespace ELMApplication.Common.DataResource
{
    public class UploadDataResource
    {
        private long _dataLength;
        private long _dataSent;
        private ELMServiceClient _client;
        private string _initParams;
        private bool _firstChunk = true;
        private bool _lastChunk = false;
        private Guid _resourceId;
        private byte[] _data;
        private string _name;
        private MemoryStream ms;
        public UploadDataResource(Guid resourceid,byte[] data,string name)
        {
           
            _data = data;
            _dataLength = _data.Length;
            ms= new MemoryStream(_data);
            _name = name;
            _resourceId=resourceid;
            _client = new ELMServiceClient();
            _client.StoreResourceCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(_client_StoreResourceCompleted);
        }

        void _client_StoreResourceCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            if (e.Error == null)
            {
             
                    UploadAdvanced();
                
            }
        }
        public event EventHandler UploadedCompled;
        public void Upload()
        {
            UploadAdvanced();
        }
        private void UploadAdvanced()
        {

            byte[] buffer = new byte[4 * 4096];

           
            int bytesRead = ms.Read(buffer, 0, buffer.Length);

            //文件是否上传完毕?
            if (bytesRead != 0)
            {
                _dataSent += bytesRead;

                if (_dataSent == _dataLength)
                    _lastChunk = true;//是否是最后一块数据，这样WCF会在服务端根据该信息来决定是否对临时文件重命名

                //上传当前数据块
                _client.StoreResourceAsync(_resourceId,_name, buffer, _firstChunk, _lastChunk);//StoreFileAdvancedAsync(_file.FileName, buffer, bytesRead, _initParams, _firstChunk, _lastChunk);


                //在第一条消息之后一直为false
                _firstChunk = false;

                //通知上传进度修改
               // OnProgressChanged();
            }
            else
            {
                //当上传完毕后
               

                _client.ChannelFactory.Close();
                if(UploadedCompled!=null)
                {
                    UploadedCompled.Invoke(this, EventArgs.Empty);
                }
            }

        }
    }
}
